import { insertOrReplace, queryAll, queryCount } from ".";
import { updateNoreadCount } from "./ChatSessionUserModel";
import { getStorageUserId } from "../plus/store/UserData";
import { isEmpty } from "../util/common";

//批量保存信息
const saveMessageBatch = (chatMessageList) => {
    return new Promise(async (resolve, _reject) => {
        const chatSessionCountMap = {};
        console.log("开始批量保存聊天信息...", chatMessageList)
        if(!isEmpty(chatMessageList) && chatMessageList.length > 0){
            chatMessageList.forEach(item => {
                let contactId = item.contactType === 1? item.contactId : item.sendUserId;
                let noReadCount = chatSessionCountMap[contactId];
                if(!noReadCount){
                    chatSessionCountMap[contactId] = 1
                }else{
                    chatSessionCountMap[contactId] = noReadCount + 1;
                }
            })
    
            //更新未读数
            for(let item in chatSessionCountMap){
                await updateNoreadCount({contactId: item, noReadCount: chatSessionCountMap[item]});
    
            }
            //批量插入
            chatMessageList.forEach(async (item) => {
                await saveMessage(item);
            })
        }
        resolve(chatMessageList.length);
    });
}

//保存信息
const saveMessage = (data) => {
    data.userId = plus.storage.getItem("userId");
    return insertOrReplace("chat_message", data);
}

//查询当前session的近20条聊天信息
const selectCurrentMessage = (sessionId) => {
    return new Promise(async (resolve, _reject) => {
        const params = [sessionId, getStorageUserId()]
        let sql = "select * from (select * from chat_message where session_id = ? and user_id = ? order by message_id desc limit 20) order by message_id";
        //计算近20条信息
        const dataList = await queryAll(sql, params);
        resolve(dataList)
    })
    
}

//上翻查询历史记录
const selectMessageList = (data) => {
    return new Promise(async (resolve, _reject) => {
        const {sessionId, pageNo, maxMessageId} = data;
        let sql = "select count(1) as totalCount from chat_message where session_id = ? and user_id = ?";
        const totalCount = await queryCount(sql, [sessionId, getStorageUserId()]);
        const {pageTotal, offset, limit} = getPageOffset(pageNo, totalCount);

        const params = [sessionId, getStorageUserId()];
        sql = "select * from (select * from chat_message where session_id = ? and user_id = ?";
        if(maxMessageId){
            params.push(maxMessageId)
            sql = sql + " and message_id < ?";
        }
        // TODO: params.push(offset)  这儿后续优化因为用到了两次排序
        params.push(limit)
        sql = sql + " order by message_id desc limit ?) order by message_id";
        const dataList = await queryAll(sql, params);

        resolve({
            dataList, pageTotal, pageNo
        })
    })
}
const getPageOffset = (pageNo, totalCount) => {
    const pageSize = 20;
    const pageTotal = totalCount % pageSize === 0 ? totalCount / pageSize : Number.parseInt((totalCount / pageSize)) + 1;
    pageNo = pageNo <= 1 ? 1 : pageNo;
    pageNo = pageNo >= pageTotal ? pageTotal : pageNo;
    console.log(`查询第${pageNo}页${pageSize}条数据，总共有${totalCount}条数据`)
    return {
        pageTotal,
        offset: (pageNo - 1) * pageSize,
        limit: pageSize
    }
}

export {
    saveMessageBatch,
    selectCurrentMessage,
    saveMessage,
    selectMessageList
}